import { useCallback, ReactElement, useMemo } from 'react';
import { Switch } from 'antd-mobile';
import { connect, useField, mapProps } from '@formily/react';
import { getMessage } from '@inbiz/react';
import { defaultProps } from '../../designer/schema';

type Iprops = {
  value: number;
  readOnly?: boolean;
  disabled?: boolean;
  onChange: (v: number) => void;
} & typeof defaultProps;

// type ref = Ref<ReturnType<typeof api> & { isValid: () => boolean }>;
const EformSwitch = (props: Iprops): ReactElement => {
  const { unCheckedChildren, checkedChildren, ...others } = props;
  const handleChange = useCallback((value: boolean) => {
    props.onChange(value ? 1 : 0);
  }, []);

  // 处理开关值 （0：关闭，1：打开）
  const formatValue = useMemo(() => {
    if (Number(props?.value) === 1) {
      return true;
    } else if (Number(props?.value) === 0) {
      return false;
    }
    return;
  }, [props.value]);

  return (
    <Switch
      {...others}
      disabled={props.readOnly || props.disabled}
      checkedText={checkedChildren}
      uncheckedText={unCheckedChildren}
      checked={formatValue}
      onChange={handleChange}
    />
  );
};

(EformSwitch as typeof EformSwitch & IDefaultValueFormat<typeof defaultProps>).defaultValueFormat =
  (props): 0 | 1 => {
    return props.defaultChecked ? 1 : 0;
  };
export default connect(
  EformSwitch,
  mapProps({}, (props, field) => {
    // const { addonAfter, prefix, ...others } = props
    // field.decoratorProps.addonAfter = addonAfter;
    // field.decoratorProps.addonBefore = prefix;
    const other = props;
    other.checkedChildren = getMessage(props.checkedChildren);
    other.unCheckedChildren = getMessage(props.unCheckedChildren);
    return { ...other };
  }),
);
